<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="3" :xs="24">
        <Tree :name="this.name" @projectSelect="isDevice" @deviceSelect="isDevice" style="margin-left: 20px;">
        </Tree>

        <!-- <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入设备名称/设备地址码" clearable size="small" prefix-icon="el-icon-search"
            filterable style="margin-bottom: 20px" />
        </div>
        <div class="head-container">

          <el-tree :props="props" ref="tree" :load="loadNode" :filter-node-method="filterNode" lazy
            @node-click="treeNodeClick">
          </el-tree>
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :check-strictly="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" :render-content="renderContent" style="font-size: 14px;" />
        </div> -->
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
           
          <el-form-item label="环境因子" prop="factorName">
            <el-select v-model="queryParams.factorName" placeholder="请选择" clearable style="width: 240px"
              @change="handleQuery">
              <el-option v-for="dict in factorOption" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="查询范围">
            <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery('1')">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['system:user:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
              v-hasPermi="['system:user:import']">导入</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2" @click="giveAlarm()">导入</el-button>
          </el-col>
          <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="selectListWarn"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="warnList" @selection-change="handleSelectionChange">
          <el-table-column label="设备ID" align="center" fixed prop="deviceId" />
          <el-table-column label="设备名称" align="center" fixed prop="deviceName" />
          <el-table-column label="因子类型" align="center" prop="factorName" />
          <el-table-column label="报警值" align="center" prop="warnVlue" />
          <el-table-column label="限值(上限/下限)" align="center" prop="limitingValue">
            <template slot-scope="scope">
              <el-tag :type="getArrowColor(scope.row.limitingValue)">{{ scope.row.limitingValue }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="记录时间" align="center" prop="recordingTime" />
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="selectListWarn" />
      </el-col>
    </el-row>
    <audio id="audio" src="../../../assets/alarm/10686.mp3"></audio>
    <!-- <audio controls>
      <source src="@/assest/alarm/10686.mp3">
    </audio> -->
  </div>
</template>

<script>
import Tree from "@/components/Tree/Tree";
import { listUser, } from "@/api/system/user";
import { listWarn, } from "@/api/system/device";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import { deptTreeSelect, NewdeptTreeSelect, listDevice } from "../../../api/system/device"
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import moment from 'moment';
export default {
  name: "User",
  dicts: ['sys_factor'],
  components: { Treeselect, Tree },
  data() {
    return {
      name: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      warnList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      //环境因子option
      factorOption: [
        {
          label: 'PM10',
          value: 'pm10'
        },
        {
          label: 'PM2.5',
          value: 'pm2.5'
        }
      ],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      props: {
        children: "children",
        label: "label",
        isLeaf: "isLeaf"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId:undefined,
        deviceName: undefined,
        beginTime: undefined,
        endTime: undefined,
        offlineTime: '',
        selectFlag: '1',
        factorName: undefined,
        deptId: undefined,
        deviceId: undefined,
      }, 
      loadingNodeId: null
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  filters: {
    formatDate(dateString) {
      return moment(dateString).format("YYYY-MM-DD HH:mm:ss");
    }
  },
  created() {
    this.name = this.$route.name
    this.selectListWarn();
    this.getDeptTree();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    isDevice(e) {
      // let param = {}
      if (e.devId) {
        this.queryParams.deviceId = e.id
        this.queryParams.deptId = ''
        // param = { deviceId: r.id }
      }
      else {
        // param = { deptId: r.id }

        this.queryParams.deviceId = ''
        this.queryParams.deptId = e.id
      }
      console.log(this.queryParams);
      this.selectListWarn()
    },
    // 懒加载树加载数据
    loadNode(node, resolve) {
      if (node.level > 0) {
        if (!node.data.children) {
          this.$set(node.data, 'children', []);
          listDevice({ status: 3, deptId: node.data.id }).then(res => {
            const newNode = res.rows.map(item => ({
              id: item.deviceId,
              label: item.deviceName
            }))
            node.data.children.push(...newNode)
          })
        }
        return resolve(node.data.children);
      }
      setTimeout(() => {
        const data = this.deptOptions
        resolve(data);
      }, 500);
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    treeNodeClick(data, node) {
      this.queryParams.deptId = ''
      this.queryParams.deviceId = ''
      // 根据当前节点层级判断
      if (node.level > 1) {
        if (data.children.length > 0) {
          this.queryParams.deptId = node.data.id
          this.queryParams.deviceId = ''
        } else {
          this.queryParams.deptId = ''
          this.queryParams.deviceId = node.data.id
        }
      }
      this.selectListWarn();
    },
    //Tree加载样式
    renderContent(h, { node, data }) {
      let label = h('span', node.label);
      // 如果当前节点正在加载数据，则显示加载图标
      if (this.loadingNodeId === data.id) {
        let loadingIcon = h('i', { class: 'el-icon-loading' });
        return h('span', [loadingIcon, label]);
      }
      // 否则只显示标签
      return label;
    },
    getArrowColor(limitingValue) {
      const arrowDirection = limitingValue.substring(0, 1);
      if (arrowDirection === '↑') {
        this.giveAlarm()
        return 'info'; // 如果箭头朝上，则设置为红色
      } else if (arrowDirection === '↓') {
        return 'warning'; // 如果箭头朝下，则设置为绿色
      }
      return ''; // 默认情况下不设置颜色
    },
    /** 查询用户列表 */
    selectListWarn() {
      this.loading = true;
      listWarn(this.queryParams).then(response => {
        this.warnList = response.rows;
        this.total = response.total;
      }).catch((err) => {
        console.log(err)
      }).finally(() => {
        this.loading = false;
      });
    },
    //发出报警声
    giveAlarm(alarmDevice) {
      // console.log(this.warnList);
      // if(this.warnList[0].limitingValue){
      let oAudio = document.querySelector("#audio");
      oAudio.onended = function () {
        //播放完毕，重新循环播放
        oAudio.load();
        oAudio.play();
      };
      // this.audioAutoPlay()
      // }

    },
    audioAutoPlay() {
      let audio = document.getElementById("audio");
      audio.play();
      document.removeEventListener("touchstart", this.audioAutoPlay);
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      NewdeptTreeSelect().then(response => {

        this.deptOptions = response.data;
        console.log(this.deptOptions)
      });
    },
    // // 筛选节点
    // filterNode(value, data) {
    //   if (!value) return true;
    //   return data.label.indexOf(value) !== -1;
    // },
    // 节点单击事件
    async handleNodeClick(data) {

      this.loadingNodeId = data.id;
      try {
        const DAta = await listDevice({ status: 3, deptId: data.id })
        this.loadingNodeId = null;

        if (!data.children) {
          this.$set(data, 'children', [])
        }
        if (DAta.rows.length > 0) {
          const newNode = DAta.rows.map(item => ({
            id: item.deviceId,
            label: item.deviceName
          }))
          data.children.push(...newNode)
          this.$refs.tree.updateKeyChildren(data.id, data.children)
        }
        this.rest()
        console.log(data)
        if (data.children.length > 0) {
          //在这里通过判断是否有children来判断是项目还是设备
          this.queryParams.deviceId = ''
          this.queryParams.deptId = data.id
        } else {
          this.queryParams.deptId = ''
          this.queryParams.deviceId = data.id
        }

        this.handleQuery();

      } catch (err) {
        this.loadingNodeId = null;
      }

    },
    isObject(obj) {
      return obj !== null && typeof obj === 'object'
    },
    // 取消按钮
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.queryParams.deviceName) {
        //搜索设备名字应该就不是点击节点触发的搜索了，所以把节点的参数都为空，树节点是通过ID查
        this.queryParams.deviceId = undefined
        this.queryParams.deptId = undefined

        this.$refs.tree.setCurrentKey(null); // 将当前选中的节点设置为null
      }
      if (this.queryParams.factorName) {
        this.queryParams.selectFlag = ''
      }
      if (!this.dateRange || this.dateRange.length === 0) {
        this.dateRange = []

      } else {
        this.queryParams.beginTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      }
      this.selectListWarn();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.rest()
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    rest() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        deviceName: undefined,
        beginTime: undefined,
        endTime: undefined,
        offlineTime: '',
        selectFlag: "1",
        factorName: undefined,
        deptId: undefined,
        deviceId: undefined,
      }
    },


    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },


  }
};
</script>
